package com.wuuxiang.polestar.core.zookeeper.surpass;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.framework.api.CuratorListener;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Preconditions;

/**
 * 项目名称：polestar        <br>
 * 类描述：                         <br>
 * 创建人：夏鸿鹏                    <br>
 * 创建时间：2017-12-5 15:44        <br>
 * 修改备注：                        <br>
 */

public class ConfigNodeSurPassEventListener implements CuratorListener {
    private static final Logger LOGGER = LoggerFactory.getLogger(ConfigNodeSurPassEventListener.class);

    private final ZookeeperSurPassConfigGroup configNode;

    public ConfigNodeSurPassEventListener(ZookeeperSurPassConfigGroup configNode) {
        super();
        this.configNode = Preconditions.checkNotNull(configNode);
    }

    @Override
    public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(event.toString());
        }

        final WatchedEvent watchedEvent = event.getWatchedEvent();
        if (watchedEvent != null) {
            LOGGER.debug("Watched event: {}" + watchedEvent);

            if (watchedEvent.getState() == KeeperState.SyncConnected) {
                boolean someChange = false;
                switch (watchedEvent.getType()) {
                    case NodeChildrenChanged:
                        configNode.loadNode();
                        someChange = true;
                        break;
                    case NodeDataChanged:
                        configNode.reloadKey(watchedEvent.getPath());
                        someChange = true;
                        break;
                    default:
                        break;
                }

                if (someChange && configNode.getConfigLocalCache() != null) {
                    configNode.getConfigLocalCache().saveLocalCache(configNode, configNode.getNode());
                }
            }
        }
    }
}
